﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.EnterpriseServices;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.Model.Manager;
using System.Data;
using YiYiTong.Rocket.Helper;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class MenuController : BaseController
    {
        #region 添加/修改菜单
        [Description("添加/修改菜单")]
        [ViewPage]
        public ActionResult AddMenu(int MenuId = 0)
        {
            MenuInfo menu = new MenuInfo();
            if (MenuId != 0)
            {
                ViewBag.Title = "修改菜单";
                menu = MenuBiz.Instance.GetMenuInfoById(MenuId);
            }
            else
                ViewBag.Title = "添加菜单";
            return View(menu);
        }

        [Description("添加/修改菜单")]
        [HttpPost]
        public ActionResult AddMenu(MenuInfo menuReq)
        {
            int ret = 0;
            string strOutPut = string.Empty;
            ResponseMsg resMsg = new ResponseMsg();
            if (ModelState.IsValid)
            {
                if (menuReq.menuId == 0)
                {
                    //添加菜单
                    ret = MenuBiz.Instance.AddMenu(menuReq.menuCode, menuReq.menuName, menuReq.menuUrl, menuReq.parentID, ConvertHelper.ConvertTo<int>(menuReq.isVisible), menuReq.remark, out strOutPut);
                }
                else
                {
                    //修改菜单
                    ret = MenuBiz.Instance.EditMenu(menuReq.menuId, menuReq.menuCode, menuReq.menuName, menuReq.menuUrl, menuReq.parentID, ConvertHelper.ConvertTo<int>(menuReq.isVisible), menuReq.remark, out strOutPut);
                }
                if (ret <= 0)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                resMsg.Message = strOutPut;
                resMsg.Body = Url.Action("MenuList", "Menu");
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = ModelState.Values.First().Errors[0].ErrorMessage;
            }
            return Json(resMsg);
        }
        #endregion

        #region 删除菜单
        [Description("删除菜单")]
        [HttpPost]
        public ActionResult DelMenu(int MenuId = 0)
        {
            int ret = 0;
            string strOutPut = string.Empty;
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.Body = Url.Action("MenuList", "Menu");
            if (MenuId != 0)
            {
                ret = MenuBiz.Instance.DeleteMenu(MenuId, out strOutPut);
                if (ret <= 0)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                resMsg.Message = strOutPut;
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "菜单不存在";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            return Json(resMsg);
        }
        #endregion

        #region 菜单列表
        [Description("查询菜单列表")]
        [ViewPage]
        public ActionResult MenuList(string menuCode = "", string menuName = "", int isVisible = -10, int pageIndex = 1, int pageSize = 10)
        {
            var ds = MenuBiz.Instance.GetPageList(menuCode, menuName, isVisible, pageIndex, pageSize);
            var allrows = ConvertHelper.ConvertTo<int>(ds.GetTable(0).Rows[0]["allrows"], 0);
            IList<MenuInfo> list = new ModelHandler<MenuInfo>().FillModel(ds, 1);
            PagedList<MenuInfo> pagedlist = null;
            if (list != null && list.Count != 0)
                pagedlist = new PagedList<MenuInfo>(list, pageIndex, pageSize, allrows);
            return View(pagedlist);
        }
        #endregion

        #region 菜单下拉框，checkbox框，获取父菜单名称
        [Description("菜单下拉框")]
        [NoVerify]
        public PartialViewResult DropListMenuList(ElementAttribute EleAttr, int ParentID = 0)
        {
            ViewBag.EleAttr = EleAttr;
            ViewBag.ParentID = ParentID;
            IList<MenuInfo> list = null;
            DataTable dt = MenuBiz.Instance.GetAllMenuList();
            if (dt != null && dt.Rows.Count != 0)
            {
                //克隆原有数据表结构
                DataTable dtmenu = dt.Clone();
                dtmenu = Utils.GetDropItems(dt, dtmenu, "MenuName", "MenuID", "0", "\u3000");
                list = new ModelHandler<MenuInfo>().FillModel(dtmenu);
            }
            return PartialView(list);
        }

        [Description("获取菜单父菜单名称")]
        [NoVerify]
        public ActionResult GetParentMenuName(int parentID)
        {
            string parentMenuName = string.Empty;
            if (parentID != 0)
            {
                parentMenuName = MenuBiz.Instance.GetMenuInfoById(parentID).menuName;
            }
            return Content(parentMenuName);
        }

        [Description("菜单checkbox列表")]
        [NoVerify]
        public PartialViewResult CheckBoxMenuList(ElementAttribute EleAttr)
        {
            ViewBag.EleAttr = EleAttr;
            IList<MenuInfo> list = null;
            DataTable dt = MenuBiz.Instance.GetAllMenuList();
            if (dt != null && dt.Rows.Count != 0)
            {
                //克隆原有数据表结构
                DataTable dtmenu = dt.Clone();
                dtmenu = Utils.GetCheckBoxItems(dt, dtmenu, EleAttr.Name, "MenuName", "MenuID", "0", "");
                list = new ModelHandler<MenuInfo>().FillModel(dtmenu);
            }
            return PartialView(list);
        }
        #endregion

        #region 菜单树状结构
        [Description("菜单checkbox列表")]
        [NoVerify]
        public string GetChkBoxMenuList(int roleId)
        {
            //获得所有Menu集合
            DataTable allMenuDt = MenuBiz.Instance.GetAllMenuList();
            List<MenuInfo> menuList = new ModelHandler<MenuInfo>().FillModel(allMenuDt);
            //获得当前用户Menu权限
            DataTable roleMenuDt = RoleBiz.Instance.GetRoleMenuList(roleId);
            List<MenuTree> treeList = new List<MenuTree>();
            FillMenuTree(menuList, treeList, null, roleMenuDt, 0);
            return JsonHelper.Serialize(treeList).Replace("m_checked", "checked");
        }

        /// <summary>
        /// 递归 填充treeList集合
        /// treeList具有层级结构
        /// </summary>
        /// <param name="menuList">所有功能集合</param>
        /// <param name="treeList">需要填充的ActionTree集合</param>
        /// <param name="tree">MenuTree对象，向该对象中添加子节点</param>
        /// <param name="roleMenuDt">当前角色拥有的Menu集合</param>
        /// <param name="parentCode">父级节点ID</param>
        private void FillMenuTree(List<MenuInfo> menuList, List<MenuTree> treeList, MenuTree tree, DataTable roleMenuDt, int parentCode)
        {
            var childMenuList = menuList.FindAll(p => p.parentID == parentCode);
            if (childMenuList.Count > 0)
            {
                foreach (var menu in childMenuList)
                {
                    MenuTree tr = GetMenuTree(menu, roleMenuDt);
                    FillMenuTree(menuList, treeList, tr, roleMenuDt, menu.menuId);
                    //tree为null时，即第一层循环，否则为进入子集递归循环过程
                    if (tree == null)
                        treeList.Add(tr);
                    else
                        tree.children.Add(tr);
                }
            }
        }

        /// <summary>
        /// 根据传入的功能实体和当前用户拥有的功能
        /// 返回功能树实体
        /// </summary>
        /// <param name="menu">Menu实体</param>
        /// <param name="roleMenuDt">用户拥有功能</param>
        /// <returns></returns>
        private MenuTree GetMenuTree(MenuInfo menu, DataTable roleMenuDt)
        {
            MenuTree tr = new MenuTree();
            tr.id = menu.menuId.ToString();
            tr.text = menu.menuName;
            tr.m_checked = IsCheckedUserHaveMenu(menu.menuId, roleMenuDt);
            return tr;
        }

        /// <summary>
        /// 返回当前用户是否拥有该功能
        /// 拥有返回True，否则False
        /// </summary>
        /// <param name="menuId">功能id</param>
        /// <param name="roleMenuDt">当前用户拥有功能列表</param>
        /// <returns></returns>
        private bool IsCheckedUserHaveMenu(int menuId, DataTable roleMenuDt)
        {
            if (roleMenuDt != null && roleMenuDt.Rows.Count > 0)
            {
                string strFilter = string.Format("menuId={0}", menuId);
                DataRow[] drs = roleMenuDt.Select(strFilter);
                return (drs != null && drs.Length != 0);
            }
            return false;
        }
        #endregion
    }
}